package com.zh.common.view.text

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.text.TextUtils
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.TextSwitcher
import android.widget.TextView
import android.widget.ViewSwitcher
import com.zh.common.R
import com.zh.common.ktx.color
import com.zh.common.ktx.sp2px
import java.util.Timer
import java.util.TimerTask

/**
 * 垂直方向走马灯效果
 */
class VerticalScrollTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : TextSwitcher(context, attrs), ViewSwitcher.ViewFactory {

    private var textSize: Float
    private var textColor: Int

    //最多显示的行数
    private var maxLines: Int
    private var ellipse: String?
    private var textStyle: Int
    private var animDirection: Int
    private var changeBgW = false

    private val dataList = mutableListOf<String>()
    private var timer: Timer? = null
    private var num = 0

    //如果想要循环的变换文字颜色的话加上这个集合
    private val colorList = mutableListOf<Int>()

    //用来判断是否开始滚动，防止重复滚动(timer执行多次schedule造成滚动的文字顺序混乱)
    private var isStart = false

    init {
        //获取属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyTextSwitcherStyle)
        textSize = typedArray.getDimension(
            R.styleable.MyTextSwitcherStyle_vst_textSize,
            15f.sp2px.toFloat()
        )
        textColor = typedArray.getColor(R.styleable.MyTextSwitcherStyle_vst_textColor, Color.BLACK)
        maxLines = typedArray.getInt(R.styleable.MyTextSwitcherStyle_vst_maxLines, 1)
        ellipse = typedArray.getString(R.styleable.MyTextSwitcherStyle_vst_ellipsize)
        textStyle = typedArray.getInt(R.styleable.MyTextSwitcherStyle_vst_textStyle, 0)
        animDirection = typedArray.getInt(R.styleable.MyTextSwitcherStyle_vst_animDirection, 0)
        changeBgW = typedArray.getBoolean(R.styleable.MyTextSwitcherStyle_vst_change_bg_w, false)
        //默认从下往上
        typedArray.recycle()
        if (changeBgW) measureAllChildren = false
        //创建动画
        when (animDirection) {
            0 -> {
                //从下往上的动画
                createBottomToTopAnimation()
            }

            1 -> {
                //从上往下
                createTopToBottomAnimation()
            }
        }
        //注意，这个setFactory()一定要写在获取属性的下方，不然在调用makeView()方法时，获取不到属性。
        setFactory(this)
    }

    override fun makeView(): View {
        Log.i("ceshi", "makeView: ")
        val textView = TextView(context)

        when (ellipse) {
            "1" -> {
                textView.ellipsize = TextUtils.TruncateAt.START
            }

            "2" -> {
                textView.ellipsize = TextUtils.TruncateAt.MIDDLE
            }

            "3" -> {
                textView.ellipsize = TextUtils.TruncateAt.END
            }

            "4" -> {
                textView.ellipsize = TextUtils.TruncateAt.MARQUEE
            }
        }
        when (textStyle) {
            1 -> {
                textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            }

            2 -> {
                textView.typeface = Typeface.defaultFromStyle(Typeface.ITALIC)
            }
        }
        if (maxLines > 0) {
            textView.maxLines = maxLines
        }
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
        textView.setTextColor(textColor)
        textView.layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        return textView
    }

    /**
     * 从下到上的动画（实现3）
     */
    private fun createBottomToTopAnimation() {
        createAnimation(
            //入场动画
            Animation.ABSOLUTE, 0f,
            Animation.ABSOLUTE, 0f,
            Animation.RELATIVE_TO_PARENT, 1f,
            Animation.ABSOLUTE, 0f,
            //出场动画
            Animation.ABSOLUTE, 0f,
            Animation.ABSOLUTE, 0f,
            Animation.ABSOLUTE, 0f,
            Animation.RELATIVE_TO_PARENT, -1f
        )
    }

    /**
     * 从上到下（实现4）
     */
    private fun createTopToBottomAnimation() {
        createAnimation(
            //入场动画
            Animation.ABSOLUTE, 0f,
            Animation.ABSOLUTE, 0f,
            Animation.RELATIVE_TO_PARENT, -1f,
            Animation.ABSOLUTE, 0f,
            //出场动画
            Animation.ABSOLUTE, 0f,
            Animation.ABSOLUTE, 0f,
            Animation.ABSOLUTE, 0f,
            Animation.RELATIVE_TO_PARENT, 1f
        )
    }

    /**
     * 具体创建动画的方法
     */
    private fun createAnimation(
        ina: Int,
        inFromXValue: Float,
        inb: Int,
        inToXValue: Float,
        inc: Int,
        inFromYValue: Float,
        ind: Int,
        inToYValue: Float,

        outa: Int,
        outFromXValue: Float,
        outb: Int,
        outToXValue: Float,
        outc: Int,
        outFromYValue: Float,
        outd: Int,
        outToYValue: Float
    ) {
        //入场动画
        val _inAnimation: Animation = TranslateAnimation(
            ina, inFromXValue,
            inb, inToXValue,
            inc, inFromYValue,
            ind, inToYValue
        )
        _inAnimation.duration = 1000
        _inAnimation.fillAfter = true
        inAnimation = _inAnimation
        //出场动画
        val _outAnimation: Animation = TranslateAnimation(
            outa, outFromXValue,
            outb, outToXValue,
            outc, outFromYValue,
            outd, outToYValue
        )
        _outAnimation.duration = 1000
        _outAnimation.fillAfter = true
        outAnimation = _outAnimation
    }


    /**
     * 点击VerticalTextSwitcher时需要知道其所属的下标位置，用户有可能会进行一些操作
     */
    fun getCurrentPosition(): Int {
        return if (dataList.size > 0) {
            num % dataList.size
        } else {
            -1
        }
    }

    /**
     * 填充数据
     */
    fun setDataList(theData: List<String>, isAutoStart: Boolean = true) {
        //防止滚动过程中处理数据发生异常
        stopScroll()

        dataList.clear()
        dataList.addAll(theData)

        if (isAutoStart) startScroll()
    }

    /**
     * 如果想要循环的变换字体颜色的话增加这个方法
     */
    fun setColorList(theData: List<Int>) {
        //防止滚动过程中处理数据发生异常
        stopScroll()

        colorList.clear()
        colorList.addAll(theData)
    }

    /**
     * 开始滚动
     * intervalTime：每隔多少秒滚动一次，可以不填写，默认是3秒切换一次，
     * todo 如何防止重复开启滚动
     */
    fun startScroll(intervalTime: Long = 3000) {
        if (timer == null) {
            timer = Timer()
        }
        if (!isStart) {
            timer?.schedule(object : TimerTask() {
                override fun run() {
                    num++
                    (context as Activity).runOnUiThread {
                        if (dataList.size > 0) {
                            setTextAndColor(dataList[num % dataList.size])
                        }
                    }
                }

            }, 0, intervalTime)
            isStart = true
        }
    }

    /**
     * 停止滚动
     */
    fun stopScroll() {
        timer?.cancel()
        timer = null
        isStart = false
    }

    /**
     * 重写setText()方法，使得其可以循环的更改文字颜色
     */
    fun setTextAndColor(text: CharSequence?, textColor: Int? = null) {
        val t = nextView as TextView
        t.text = text
        textColor?.let { t.setTextColor(context.color(textColor)) }
        showNext()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopScroll()
    }
}